<template>
  <div class="earnings">
    <div class="earnings-header clearfloat">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/mechanism/home/menu' }"
          >首页</el-breadcrumb-item
        >
        <el-breadcrumb-item>我的收益</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="fr">
        <el-button @click="lastMonthSettlement">上月结算明细</el-button>
        <!-- <el-button @click="issueAnInvoice">开票</el-button> -->
        <orderStatistics
          :myInfo="myInfo"
          :roleID="roleID"
          @getData="getTableData"
        />

        <table-search
          class="clearfloat fr"
          ref="table-search"
          :isGetAgent="false"
          :selectHead="selectHead"
          @searchMethods="searchMethods"
        >
        </table-search>
        <!-- <el-button type="text"
          
          class="fr mr20 exportExcel"
          icon='el-icon-download'
          @click="exportExcel('我的收益')"
          v-no-more-click:3000>
          导出列表
        </el-button> -->
        <exportExcel
          v-if="$store.state.user.vip != 0"
          :downLoadList.sync="downLoadList"
          class="fr"
          ref="exportExcel"
          :excelName="excelName"
          @exportExcel="exportExcel(arguments)"
        >
        </exportExcel>
      </div>
    </div>
    <div class="earnings-main" ref="watermark">
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        v-loading="loading"
        height="100%"
        @row-click="selectRow"
        @selection-change="selectionChange"
        @sort-change="tableSortChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          show-overflow-tooltip
          label="订单编号"
          prop="order_number"
          sortable="custom"
          min-width="200"
        ></el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="type"
          label="专利类型"
          min-width="120"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.final">
              {{ scope.row.final.type | typeFilter }}
            </span>
            <span v-else>
              {{ scope.row.type }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="name"
          label="案件名称"
          min-width="150"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.final">
              {{ scope.row.final.name | getNullVal }}
            </span>
            <span v-else>
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="liaisons"
          label="联络人"
          min-width="120"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.final">
              <template v-if="scope.row.final.order">
                {{ scope.row.final.order.liaisons | getNullVal }}
              </template>
              <template v-else> 无 </template>
            </span>
            <span v-else> 无 </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          show-overflow-tooltip
          prop="invoice_status"
          label="开票状态"
          min-width="140"
          sortable="custom"
        >
          <template slot="header">
            <span>开票状态</span>
          </template>
          <template slot-scope="scope">
            <span
              :class="
                scope.row.invoice_status == 1 ? 'font_success' : 'font_danger'
              "
              >{{ scope.row.invoice_status | invoiceStatus }}</span
            >
          </template>
        </el-table-column> -->
        <el-table-column
          show-overflow-tooltip
          prop="settlements_price"
          label="结算金额"
          min-width="140"
          sortable="custom"
        >
          <template slot="header">
            <span>结算金额(元)</span>
          </template>
          <template slot-scope="scope">
            <span class="settlementColor">{{ scope.row.prices }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="reward"
          label="案件奖励"
          min-width="140"
          sortable="custom"
        >
          <template slot="header">
            <span>案件奖励(元)</span>
          </template>
          <template slot-scope="scope">
            <span
              :class="
                Number(scope.row.reward) != 0
                  ? 'rewardColor isValue'
                  : 'rewardColor'
              "
              @click.stop="rewardInfo(scope.row)"
              >+{{ scope.row.reward }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="deduction"
          label="扣款金额"
          min-width="140"
          sortable="custom"
        >
          <template slot="header">
            <span>扣款金额(元)</span>
          </template>
          <template slot-scope="scope">
            <span
              :class="
                Number(scope.row.deduction) != 0
                  ? 'deductionsColor isValue'
                  : 'deductionsColor'
              "
              @click.stop="deductionInfo(scope.row)"
              >-{{ scope.row.deduction }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="actual_amount"
          label="实际金额"
          sortable="custom"
          min-width="140"
        >
          <template slot="header">
            <span>实际金额(元)</span>
          </template>
          <template slot-scope="scope">
            <span class="reallyColor">{{ scope.row.actual_amount }}</span>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="settlements_name"
          label="结算类型"
          min-width="120"
          sortable="custom"
        >
          <template slot-scope="scope">
            <template v-if="scope.row.settlements_name == '导入结算'">
              {{ scope.row.settlements_name }}</template
            >
            <template v-else>
              {{ scope.row.settlements_name | getNullVal }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="grades"
          label="平均评分"
          min-width="120"
          sortable="custom"
        >
          <template slot-scope="scope">
            <template>
              <span>{{
                scope.row.final && scope.row.final.grades
                  ? getAverage(scope.row.final.grades)
                  : ""
              }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="created_at"
          label="结算时间"
          min-width="180"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ scope.row.created_at | getNullVal }}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="earnings-bottom">
      <pagination
        @paginationChange="paginateChange"
        :total="total"
      ></pagination>
    </div>

    <!-- 查看评分页面 -->
    <earningsInfo ref="earningsInfo" />
    <!-- 扣款信息查看界面 -->
    <earningsDeduction ref="earningsDeduction" />
    <!-- 上月结算明细 -->
    <lastMonthSettlement ref="lastMonthSettlement"></lastMonthSettlement>

    <!-- 奖励信息界面 -->
    <earningsReward ref="earningsReward" />

    <!-- 开票 -->
    <issueAnInvoiceDialog ref="issueAnInvoiceDialog" @refresh='getTableData' />
  </div>
</template>

<script>
import Pagination from "~/components/pagination";
import tableSearch from "~/components/tableSearch";
import orderStatistics from "~/components/orderStatistics";
import earningsInfo from "./components/earnings-info";
import earningsDeduction from "./components/earnings-deduction";
import lastMonthSettlement from "./components/lastMonthSettlement";
import { getMyInfo } from "~/api/user";
import exportExcel from "~/components/excelExport";
import earningsReward from "./components/earnings-reward";
import Watermark from "./components/watermark";
import issueAnInvoiceDialog from './components/issueAnInvoice-dialog'
export default {
  components: {
    Pagination,
    tableSearch,
    earningsInfo,
    orderStatistics,
    earningsDeduction,
    lastMonthSettlement,
    exportExcel,
    earningsReward,
    issueAnInvoiceDialog
  },
  data() {
    return {
      tableData: [],
      loading: false,
      pageSize: 25, //一页可以几条
      // currentPage: 1, //目前在第几页
      // tableSize: 25, //一页几条
      total: 0,
      selectHead: [
        {
          label: "订单编号",
          props: "order_number",
        },
        {
          label: "专利类型",
          props: "type",
        },
        {
          label: "案件名称",
          props: "name",
        },
        {
          label: "联络人",
          props: "liaisons",
        },
        {
          label: "扣款情况",
          props: "deduction",
        },
        {
          label: "案件奖励",
          props: "reward",
        },
        {
          label: "结算金额",
          props: "settlements_price",
        },
        {
          label: "结算状态",
          props: "settlement_status",
        },
        {
          label: "结算类型",
          props: "settlements_name",
        },

        {
          label: "定稿时间",
          props: "createdTime",
          isDetailsTime: true,
        },
      ],
      paramsByOrder: {},
      myInfo: {
        last_mon_total: 0,
        mon_total: 0,
      },
      roleID: 2,
      downLoadList: [
        {
          label: "订单编号",
          isSelect: true,
          props: "order_number",
        },
        {
          label: "专利类型",
          isSelect: true,
          props: "type",
        },
        {
          label: "案件名称",
          isSelect: true,
          props: "finalName",
        },
        {
          label: "联络人",
          isSelect: true,
          props: "liaisons",
        },
        // {
        //   label: "开票状态",
        //   isSelect: true,
        //   props: "invoice_status",
        // },
        {
          label: "结算金额",
          isSelect: true,
          props: "prices",
        },
        {
          label: "案件奖励",
          isSelect: true,
          props: "reward",
        },
        {
          label: "扣款金额",
          isSelect: true,
          props: "deduction",
        },
        {
          label: "实际金额",
          isSelect: true,
          props: "actual_amount",
        },
        {
          label: "结算类型",
          isSelect: true,
          props: "settlements_name",
        },
        {
          label: "平均评分",
          isSelect: true,
          props: "grades",
        },
        {
          label: "定稿时间",
          isSelect: true,
          props: "created_at",
        },
      ],
      excelName: "我的收益",
      tableSelect: [],
    };
  },
  filters: {
    invoiceStatus(val) {
      switch (val) {
        case 1:
          return "已开票";
        case 2:
          return "未开票";
      }
    },
  },

  created() {
    this.getTableData();
  },
  mounted() {
    let user = JSON.parse(sessionStorage.getItem("store"));
    let name = "";
    if (user) {
      name = user.user.name;
    } else {
      name = this.$store.state.user.name || "";
    }
    Watermark.set(name, this.$refs.watermark);
  },
  methods: {
    issueAnInvoice() {
      if (this.tableSelect.length == 0) {
        this.$message({
          message: "请至少选择一个订单！",
          type: "warning",
        });
        return;
      }
      this.$refs['issueAnInvoiceDialog'].show(this.tableSelect)
      // let orderId = [];
      // let sumMoney = null;
      // for (let i = 0; i < this.selectionInvArr.length; i++) {
      //   orderId.push(this.selectionInvArr[i].id);
      //   sumMoney += Number(this.selectionInvArr[i].money);
      // }
      // this.form.money = sumMoney;
      // this.form.invoiceRecord = orderId.join(",");
      // this.dialogFormVisible = true;
    },
    selectionChange(val) {
      this.tableSelect = val;
    },
    gwm() {
      //水印,非管理员要设置
      if (
        this.$store.state.user.role_id != 1 &&
        this.$route.path != "/admin/register" &&
        this.$route.path != "/admin/personalCenter/dstribution" &&
        this.$route.path != "/admin/personalCenter/myPurse" &&
        this.$route.path != "/admin/activityList/activityConfig" &&
        this.$route.path != "/admin/activityList/sysConfig" &&
        this.$route.path != "/admin/login" &&
        this.$route.path != "/admin/agentImprove" &&
        this.$route.path != "/order/login"
      ) {
        let that = this;
        let gwm = require("gwm");
        gwm.creation({
          txt: that.$store.state.user.name,
          container: ".el-table", //#gwm
          fontSize: 40,
          alpha: 0.3,
          css: true,
        });
      }
    },
    //导出excel
    exportExcel(args) {
      let params = {
        allPage: 2,
      };
      if (!args[1]) {
        params = { ...params, ...this.paramsByOrder, ...this.search_params };
      }
      this.$refs.exportExcel.downloadLoading = true;
      this.$axios.get("api/settlement", { params: params }).then((res) => {
        if (res.data.code == 200) {
          this.$refs.exportExcel.downloadLoading = false;
          if (res.data.data.length == 0) {
            this.$alert("暂无收益", "提示", {
              confirmButtonText: "确定",
              center: true,
              type: "warning",
              callback: (action) => {},
            });
            return;
          }
          let exTableData = [];
          let item = {};
          for (let i in JSON.parse(JSON.stringify(res.data.data))) {
            item = res.data.data[i];
            exTableData.push(item);
          }
          this.$refs.exportExcel.exportExcelEarnings(
            args[0],
            this.downLoadList,
            exTableData
          );
        } else {
          this.$refs.exportExcel.downloadLoading = false;
          this.$alert(res.data.message, "提示", {
            confirmButtonText: "确定",
            center: true,
            type: "warning",
            callback: (action) => {},
          });
        }
      });
    },
    getAverage(value) {
      return (value.total_score / 3).toFixed(1);
    },
    async getMyinfo(params) {
      let myInfo = await getMyInfo(this.$axios, params);
      if (myInfo.data.status == "success") {
        this.$store.commit("setRoleInfo", myInfo.data.data);
        this.$store.commit("setUser", myInfo.data.data);
        // this.myInfo = myInfo.data.data
      }
    },
    getTableData(args) {
      let params = {
        perPage: this.pageSize,
        page: this.currentPage,
      };
      params = { ...params, ...this.paramsByOrder, ...this.search_params };
      if (args) {
        params = { ...params, ...args };
        params.is_finish = 1;
      }
      this.loading = true;
      this.$axios
        .get("api/settlement", {
          params: params,
        })
        .then((res) => {
          if (res.data.code == 200) {
            this.loading = false;
            this.tableData = res.data.data;
            this.pageSize = res.data.page.per_page;
            this.total = res.data.page.total;
            this.myInfo = res.data.count;
            this.getMyinfo();
          } else {
            this.loading = false;
            this.$message.error("服务器繁忙");
          }
        });
    },
    deductionInfo(row) {
      if (row.deduction != 0) {
        this.$refs["earningsDeduction"].show(row);
      }
    },
    rewardInfo(row) {
      if (row.final && row.final.settlement_reward_record.length != 0) {
        this.$refs["earningsReward"].show(row);
      }
    },
    searchMethods(params, no_search) {
      this.sort_params = {};
      this.currentPage = 1;
      this.pageSize = 25;
      this.search_params = params;
      if (params.createdTime) {
        params.created_start_time = params.createdTime[0];
        params.created_end_time = params.createdTime[1];
        delete params.createdTime;
      }
      if (!no_search) {
        this.getTableData();
      }
    },
    paginateChange(params) {
      this.pageSize = params.perPage;
      this.currentPage = params.page;
      this.getTableData();
    },
    tableSortChange(column) {
      if (column.order === "descending") {
        this.paramsByOrder.sort_str = column.prop;
        this.paramsByOrder.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.paramsByOrder.sort_str = column.prop;
        this.paramsByOrder.sort_order = "asc";
      } else {
        delete this.paramsByOrder.sort_str;
        delete this.paramsByOrder.sort_order;
      }
      this.loading = true;
      this.currentPage = 1;
      this.getTableData();
    },
    selectRow(row) {
      if (window.getSelection().toString() === "") {
        this.$refs.earningsInfo.show(row);
      }
    },
    lastMonthSettlement() {
      this.$refs["lastMonthSettlement"].show();
    },
  },
};
</script>

<style lang='less'>
.earnings {
  width: 90%;
  height: 100%;
  margin: 0 auto;
  padding: 25px 30px 0 30px;
  background: #fff;
  display: flex;
  flex-direction: column;
  .el-table__body-wrapper {
    opacity: 0.7;
  }
  &-header {
    // height: 45px;
    flex: 0 0 45px;
    .el-breadcrumb {
      .el-breadcrumb__item {
        .el-breadcrumb__inner,
        .el-breadcrumb__separator {
          font-size: 25px;
          color: rgba(0, 35, 151, 1);
          font-weight: 400;
        }
      }
      .el-breadcrumb__item:first-child {
        .el-breadcrumb__inner {
          padding-left: 10px;
          border-left: 5px solid #002397;
        }
      }
    }
    box-sizing: border-box;

    .el-button {
      border: 1px solid rgba(36, 157, 255, 1);
      border-radius: 12px;
      padding: 5px 16px;
      color: #31a3ff;
      font-size: 15px;
      margin: 0 20px 10px 0;
    }
    .el-button:hover {
      background: rgba(36, 157, 255, 1);
      color: #fff;
    }
    .el-button:focus {
      background: rgba(36, 157, 255, 1);
      color: #fff;
    }
  }
  &-main {
    flex: 1;
    max-height: calc(100% - 115px);

    .tableText {
      color: #353535;
    }
    .settlementColor {
      color: #e4c100;
    }
    .rewardColor {
      color: #1ab700;
    }
    .deductionsColor {
      color: #cb0000;
    }
    .reallyColor {
      color: #0084e9;
    }

    .isValue {
      text-decoration: underline;
      cursor: pointer;
    }
  }
  &-bottom {
    flex: 0 0 70px;
    padding-top: 19px;
  }
}
</style>
